package net.lzzy.practices.aspects;

import net.lzzy.practices.entities.User;
import net.lzzy.practices.services.UserService;
import net.lzzy.practices.utils.AspectUtil;
import net.lzzy.practices.utils.JwtUtil;
import net.lzzy.practices.web.models.ApiResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.UUID;

/**
 * @author admin
 */
@Aspect
@Component
public class AdminAspect {

    private final UserService service;

    @Autowired
    private AdminAspect(UserService service) {
        this.service = service;
    }

    @Pointcut("execution(* net.lzzy.practices.web.admin.UserApiController.*(..))")//用于定义切入点的注解

    public void adminPoint(){}

    @Around("adminPoint()") //用于定义环绕通知
    public ApiResult aroundAdminController(ProceedingJoinPoint point) throws Throwable {

        //token参数的3种形式: 1.直接列在方法参数中 2.使用了Info参数类BaseInfo 3.使用JSONObject对象

        String token = AspectUtil.getToken(point);
        String uid = JwtUtil.verifyToken(token);
        if (uid == null){
            return new ApiResult(false,"认证信息已失效，请重新登录!",null);

        }
        User user = service.getById(UUID.fromString(uid));
        if (user == null){
            return  new ApiResult(false,"认证信息无效，请登录",null);
        }
        int[] allowRoles = new int[]{User.TYPE_ADMIN};
        if(Arrays.stream(allowRoles).noneMatch(role -> role == user.getType())){
            return new ApiResult(false,"没有权限，请登录为管理员！",null);
        }
        return (ApiResult) point.proceed();
    }

}
//456